package com.itheima.reggie.web.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.entity.AddressBook;
import com.itheima.reggie.service.AddressBookService;
import com.itheima.reggie.utils.ThreadLocalUtil;
import com.itheima.reggie.web.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @Author Vsunks.v
 * @Blog blog.sunxiaowei.net/996.mba
 * @Description: 地址管理类
 */
@Slf4j
@RestController
@RequestMapping("/addressBook")
public class AddressBookController {
    @Autowired
    private AddressBookService addressBookService;


    /**
     * 查询当前登录用户的所有收货地址，
     * 隐含条件为当前登录用户的id，可以通过ThreadLocal获取
     *
     * @return
     */
    @GetMapping("/list")
    public R<List<AddressBook>> list() {
        // 从当前线程绑定对象中获取用户id
        Long userId = ThreadLocalUtil.getCurrentId();

        log.info("查询用户【{}】的所有收货地址", userId);

        // 查询所有地址，查询条件：当前登录的用户id
        LambdaQueryWrapper<AddressBook> querywrapper = new LambdaQueryWrapper<>();
        // 设置查询条件：用户id
        // 设置隐含查询条件：默认地址队首，按照修改时间倒序排列
        querywrapper.eq(AddressBook::getUserId, userId)
                .orderByDesc(AddressBook::getIsDefault)
                .orderByDesc(AddressBook::getUpdateTime);
        List<AddressBook> addressBooks = addressBookService.list(querywrapper);

        return R.success("查询所有地址成功", addressBooks);
    }


    /**
     * 新增收货地址，需要补充当前登录用户id
     *
     * @param addressBook 收货地址，无收货人id
     * @return
     */
    @PostMapping
    public R save(@RequestBody AddressBook addressBook) {

        // 获取当前登录用户id
        Long userId = ThreadLocalUtil.getCurrentId();
        addressBook.setUserId(userId);

        boolean saveResult = addressBookService.save(addressBook);

        if (saveResult) {
            return R.success("保存收货地址成功");
        }
        return R.fail("保存收货地址失败");
    }

    /**
     * 根据id查询
     *
     * @param id 要查询的id
     * @return
     */
    @GetMapping("/{id}")
    public R getById(@PathVariable Long id) {
        log.info("根据id查询：{}", id);


        if (id != null) {

            AddressBook addressBook = addressBookService.getById(id);

            if (addressBook != null) {
                return R.success("查询成功", addressBook);
            }
            return R.fail("查询失败");
        }

        return R.fail("参数有误");
    }

    /**
     * 修改地址
     * 1. 检查地址中userId是否为空，为空则不允许修改
     *
     * @param addressBook
     * @return
     */
    @PutMapping
    public R update(@RequestBody AddressBook addressBook) {
        log.info("修改地址信息：{}", addressBook.toString());

        // 检查参数是否为空，为空则不允许修改
        if (addressBook != null && addressBook.getId() != null) {
            // 提交修改
            boolean updateResult = addressBookService.updateById(addressBook);
            if (updateResult) {
                return R.success("修改成功");
            }
            return R.fail("修改失败");
        }
        return R.fail("参数有误，id不能为空");
    }

    /**
     * 设置默认收货地址
     *
     * @param addressBook 默认的收货地址id
     * @return
     */
    @PutMapping("/default")
    public R setDefaultAddress(@RequestBody AddressBook addressBook) {
        log.info("设置默认收货地址：{}", addressBook.getId());

        // 检查参数是否为空，为空则不允许修改
        if (addressBook != null && addressBook.getId() != null) {

            // 提交修改
            boolean updateResult = addressBookService.setDefaultAddress(addressBook);
            if (updateResult) {
                return R.success("修改成功");
            }
            return R.fail("修改失败");
        }
        return R.fail("参数有误");

    }


    /**
     * 按照id删除，支持批量删除
     *
     * @param ids
     * @return
     */
    @DeleteMapping
    public R removeByIds(@RequestParam("ids") List<Long> ids) {

        boolean batchRemoveResult = addressBookService.removeByIds(ids);
        if (batchRemoveResult) {
            return R.success("删除成功");
        }
        return R.fail("删除失败");
    }


    /**
     * 查询默认地址。
     * 隐含条件：
     * 1. 当前登录用户id
     * 2. 地址为默认地址，is_default=1
     */
    @GetMapping("default")
    public R<AddressBook> getDefault() {

        // 获取用户id
        Long userId = ThreadLocalUtil.getCurrentId();

        log.info("查询当前登录用户【{}】的默认收货地址", userId);

        // 构造条件对象，封装查询条件
        LambdaQueryWrapper<AddressBook> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AddressBook::getUserId, userId)
                .eq(AddressBook::getIsDefault, 1);
        AddressBook addressBook = addressBookService.getOne(queryWrapper);
        if (addressBook != null) {
            return R.success("默认收货地址查询成功", addressBook);
        }
        return R.fail("无默认收货地址");
    }
}
